package at.moop.up;

import android.content.Intent;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.nfc.NfcAdapter.CreateNdefMessageCallback;
import android.nfc.NfcEvent;
import android.os.Bundle;
import android.os.Parcelable;
import android.preference.PreferenceActivity;
import android.util.Log;
import android.view.Menu;
import android.widget.Toast;

public class MainActivity extends PreferenceActivity implements CreateNdefMessageCallback {
	
	NfcAdapter nfc;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		addPreferencesFromResource(R.xml.preferences);
		
		nfc = NfcAdapter.getDefaultAdapter(this);
		if(nfc != null){
			nfc.setNdefPushMessageCallback(this, this);
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		//getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	@Override
	public NdefMessage createNdefMessage(NfcEvent arg0) {
		String text = UpSoldier.getFtpCredentials(getApplicationContext()).toString();
		NdefMessage msg = new NdefMessage(
				new NdefRecord[] {
						NdefRecord.createMime("application/at.moop.up.beam.preferences", text.getBytes())
				});
		return msg;
	}
	
	@Override
    public void onResume() {
        super.onResume();
        // Check to see that the Activity started due to an Android Beam
        if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(getIntent().getAction())) {
            processIntent(getIntent());
        }
    }
	
	@Override
    public void onNewIntent(Intent intent) {
        // onResume gets called after this to handle the intent
        setIntent(intent);
    }
	
	void processIntent(Intent intent) {
        Parcelable[] rawMsgs = intent.getParcelableArrayExtra(
                NfcAdapter.EXTRA_NDEF_MESSAGES);
        // only one message sent during the beam
        NdefMessage msg = (NdefMessage) rawMsgs[0];
        // record 0 contains the MIME type, record 1 is the AAR, if present
        String text1 = new String(msg.getRecords()[0].getPayload());
        FTPCredentials c = new FTPCredentials();
        c.createFromString(text1);
        Log.i("MainActivity", "New credentials: "+c.toString());
        UpSoldier.storeCredentials(c, getApplicationContext());
        Toast.makeText(getApplicationContext(), "Danke dir!", Toast.LENGTH_SHORT).show();
        setPreferenceScreen(null);
        addPreferencesFromResource(R.xml.preferences);
    }

}
